package cn.xfdzx.android.apps.shop.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.PaymentDeskOrderActivity;
import cn.xfdzx.android.apps.shop.activity.login.OneLoginMainActivity;
import cn.xfdzx.android.apps.shop.adapter.OrderListAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpFragment;
import cn.xfdzx.android.apps.shop.bean.AfterSalesListMarketBean;
import cn.xfdzx.android.apps.shop.bean.AfterSalesListRetailBean;
import cn.xfdzx.android.apps.shop.bean.ConfirmBeen;
import cn.xfdzx.android.apps.shop.bean.NewOrderBeen;
import cn.xfdzx.android.apps.shop.bean.OrderListBeen;
import cn.xfdzx.android.apps.shop.bean.ReturnReasonBean;
import cn.xfdzx.android.apps.shop.contract.OrderListContract;
import cn.xfdzx.android.apps.shop.evenbus.OrderMoneyMessage;
import cn.xfdzx.android.apps.shop.evenbus.UpdateMessage;
import cn.xfdzx.android.apps.shop.evenbus.UpdateMyOrderMessage;
import cn.xfdzx.android.apps.shop.presenter.OrderListPresenter;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.TimeUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static cn.xfdzx.android.apps.shop.activity.MainActivity.TYPE_IS_RETAIL;
import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;
import static cn.xfdzx.android.apps.shop.apps.Constants.WX_APP_ID;

/**
 * @author gzk
 * @date 2020/3/26 0026
 * description：全部订单
 */
public class AllOrderFragment extends BaseMvpFragment<OrderListPresenter> implements OrderListContract.View {

    private static final String TAG = "AllOrderFragment";
    @BindView(R.id.rv_all_order)
    RecyclerView rvAllOrder;
    @BindView(R.id.ll_hint)
    LinearLayout llHint;
    SmartRefreshLayout mRefreshLayout;


    private OrderListAdapter orderListAdapter;
    private int page = 1;
    private int limit = Constants.LIMIT;
    private String type;
    private List<OrderListBeen.DataBean> mList = new ArrayList();
    private IWXAPI api;
    String sales_model;
    int finshTimeOrder = 15 * 60;//剩余支付时间

    @Override
    protected void initView(View view) {
        EventBus.getDefault().register(this);
//        rvAllOrder = view.findViewById(R.id.rv_all_order);
        mRefreshLayout = view.findViewById(R.id.refreshLayout);

        mPresenter = new OrderListPresenter();
        mPresenter.attachView(this);
        if (TYPE_IS_RETAIL == 0) {
            sales_model = "0";
        } else {
            sales_model = "1";
        }
        api = WXAPIFactory.createWXAPI(getActivity(), WX_APP_ID);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvAllOrder.setLayoutManager(linearLayoutManager);
        rvAllOrder.setItemAnimator(new DefaultItemAnimator());
        orderListAdapter = new OrderListAdapter(getContext(), mList, mPresenter);
        rvAllOrder.setAdapter(orderListAdapter);
        type = getArguments().getString("type");
        orderListAdapter.setPagePosition(type);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.initData(true, false, type, sales_model, page + "", limit + "");
                if (disposable != null) {
                    disposable.dispose();
                }
            }
        });

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_all_order;
    }

    @Override
    public void showLoading() {
        if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
            ProgressDialog.getInstance().show(getActivity());
        }
    }

    private Disposable disposable;

    @Override
    public void hideLoading() {

        ProgressDialog.getInstance().dismiss();

    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void XXX(UpdateMyOrderMessage messageEvent) {
        //viewPage滑动到哪个就刷新哪个
        if (messageEvent.getMessage().equals(getArguments().getString("type"))) {
            page = 1;
            mList.clear();
            orderListAdapter.notifyDataSetChanged();
            mPresenter.initData(true, true, type, sales_model, page + "", limit + "");

            if (disposable != null) {
                disposable.dispose();
            }
        }

    }

    @Override
    public void onError(Throwable throwable) {
        Log.e("异常", throwable.toString());
    }

    @Override
    public void onOrderListSuccess(OrderListBeen bean) {
        if (disposable != null) {
            disposable.dispose();
        }
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (page == 1) {
                mList.clear();
                mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                    @Override
                    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                        mPresenter.initData(false, false, type, sales_model, page + "", limit + "");
                    }
                });
            }
            if (bean.getData().size() == 0) {
                mRefreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                page++;
            }
            mList.addAll(bean.getData());
            orderListAdapter.notifyDataSetChanged();
            long time = System.currentTimeMillis() / 1000;
            for (OrderListBeen.DataBean dataBean : mList) {
                if (dataBean.getPaid() == 0) {
                    long creat = Long.parseLong(Utils.date2TimeStamp(dataBean.getCreated_at(), "yyyy-MM-dd HH:mm:ss")) / 1000;
                    if (time - creat < finshTimeOrder) {
                        int miao = (int) (creat + finshTimeOrder - time);
                        dataBean.setMiao(miao);
                        Log.e("messageEvent", "---messageEvent" + miao);
                        Observable.interval(1, TimeUnit.SECONDS)
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribeOn(Schedulers.io())
                                .subscribe(new Observer<Long>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {
                                        Log.d(TAG, "--messageEvent: " + d.toString());
                                        disposable = d;
                                    }

                                    @Override
                                    public void onNext(Long aLong) {
                                        Log.d(TAG, "--messageEvent: " + aLong);
                                        int s = (int) (miao - aLong);
                                        dataBean.setMiao(s);

                                        if (s == 0) {
                                            disposable.dispose();
                                        }
                                        orderListAdapter.notifyDataSetChanged();
                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }

                                    @Override
                                    public void onComplete() {
                                        Log.d(TAG, "--messageEvent: ");
                                    }
                                });

                    }
                }

            }


            if (mList.size() == 0) {
                llHint.setVisibility(View.VISIBLE);
            } else {
                llHint.setVisibility(View.GONE);
            }
        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(getActivity(), "login").remove("head_url");
                UtilsData.getPreference(getActivity(), "login").remove("nickname");
                UtilsData.getPreference(getActivity(), "login").remove("is_store");
                UtilsData.getPreference(getActivity(), "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(getActivity(), OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getRefundRreasonSuccess(ReturnReasonBean bean) {

    }

    @Override
    public void getAfterServiceRequestSuccess(ReturnReasonBean bean) {

    }

    @Override
    public void getReturnReasonSuccess(ReturnReasonBean bean) {

    }


    @Override
    public void finishRefresh() {
        mRefreshLayout.finishRefresh(true);//刷新完成
    }

    @Override
    public void finishLoadMore() {
        mRefreshLayout.finishLoadMore(true);//加载完成
    }

    @Override
    public void onPaySuccess(NewOrderBeen bean, int position) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            EventBus.getDefault().post(new OrderMoneyMessage(mList.get(position).getTotal_price(), "  "));


            boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
            if (isPaySupported) {
                PayReq req = new PayReq();
                req.appId = bean.getData().getResult().getJsConfig().getAppid();
                req.partnerId = bean.getData().getResult().getJsConfig().getPartnerid();
                req.prepayId = bean.getData().getResult().getJsConfig().getPrepayid();
                req.nonceStr = bean.getData().getResult().getJsConfig().getNoncestr();
                req.timeStamp = bean.getData().getResult().getJsConfig().getTimestamp() + "";
                req.packageValue = bean.getData().getResult().getJsConfig().getPackageX();
                req.sign = bean.getData().getResult().getJsConfig().getSign();
                req.extData = "";
                api.sendReq(req);
            } else {
                Toast.makeText(getActivity(), "当前微信版本不支持支付", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onConfirmSuccess(ConfirmBeen bean, int position) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            mList.remove(position);
            orderListAdapter.notifyDataSetChanged();
        } else if (bean.getStatus() == 2000) {
            Toast.makeText(getActivity(), "此商铺已打烊", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onGetAfterSalesRetailListSuccess(AfterSalesListRetailBean bean) {

    }

    @Override
    public void onGetIsExceedTimeSuccess(AfterSalesListRetailBean bean) {

    }

    @Override
    public void onGetAfterSalesMarketListSuccess(AfterSalesListMarketBean bean) {

    }

    public static AllOrderFragment newInstance(String type) {
        Bundle bundle = new Bundle();
        bundle.putString("type", type + "");
        AllOrderFragment fragment = new AllOrderFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onDestroy() {
        mList.clear();
        mList = null;
        orderListAdapter.notifyDataSetChanged();
        if (disposable != null) {
            disposable.dispose();
        }
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        Log.e(TAG, "onDestroy: 22222222222222222222222222222222");

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (disposable != null) {
            disposable.dispose();
        }
        mList.clear();
        orderListAdapter.notifyDataSetChanged();
        super.onDestroyView();


    }


}
